<template>
    <s-layout id="layout" :title="'新增日收益'" navbar="normal" leftIconColor="#ffffff" :autoBack="true" :bgColor="'rgba(0,0,0,0)'" :tabbarshow='false' :titleStyle="{ color: '#ffffff', fontSize: '32rpx',fontWeight:'600' }">
        <!-- 最大盒子 -->
        <view class="container" :style="{ backgroundImage: `url( ${baseUrl}/uploads/uniapp_image/staff/staff_project_arrange.png)`,paddingTop:(safeAreaInsets?.top + 44) + 'px'}">
            <view class="area form_box">
                <scroll-view scroll-y style="height: 70vh" :enable-back-to-top="true">
                    <u--form :labelStyle="labelStyle" labelPosition="left" :model="FormData" :rules="rules" ref="formRole" :borderBottom="false">
                    <!-- 项目 -->
                    <u-form-item :required="true" @tap="projectSwitch" :borderBottom="false" :labelWidth="100" label="部门：" prop="department_id" ref="department_id">
                        <u--input :clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请选择部门" v-model="project_title" border="none"></u--input>
                    </u-form-item>
                    <!-- 时间 -->
                    <u-form-item :required="true" :borderBottom="false" :labelWidth="100" label="时间：" prop="date" ref="date">
                        <!-- dateRange -->
                        <view class="date_range" @tap="dateRange">
                            <view class="date_image">
                                <image :src="`${baseUrl}/uploads/uniapp_image/staff/class_icon01.png`"  mode="scaleToFill"/>
                            </view>
                            <view class="range_time">{{ FormData.date ? FormData.date : '请选择时间' }}</view>
                        </view>
                    </u-form-item>
                    <!-- 班次 -->
                    <u-form-item :required="true" :borderBottom="false" :labelWidth="100" label="班次：" prop="classes" ref="classes">
                        <view @tap="SoonerOrLater">
                            <view class="range_time right_margin" v-if="FormData.department_id == ''">请先选择部门</view>
                            <view class="range_time right_margin" v-else>{{ FormData.classes ? classes_title : '请选择班次' }}</view>
                        </view>
                    </u-form-item>
                    <!-- 类型 -->
                    <u-form-item :borderBottom="false" :labelWidth="100" label="类型：">
                        <u--input :clearable="false" disabledColor="rgba(0,0,0,0)" disabled inputAlign="right" type="text" placeholder="请先选择部门" v-model="type_text" border="none"></u--input>
                    </u-form-item>
                    <!-- 收入 -->
                    <view class="message">
                        收入
                        <view class="glide"></view>
                    </view>
                    <view class="num_price" v-for="(item,index) of projectprice" :key="index">
                        <view class="input_box">
                            <u-form-item  :required="true" :borderBottom="false" :labelWidth="100" :label="'数量' + `(${type_text.substr(1, 2)})` + ':'" :prop="num_price_tmp['num_price'+index]" :ref="num_price_tmp['num_price'+index]">
                                <u--input :clearable="false" @change="changeNum(item,index)" type="digit" :placeholder=" type_text == '计时' ? '请输入工时数' : '请输入数量'" v-model.lazy="item.num" border="none"></u--input>
                            </u-form-item>
                        </view>
                        <view class="price_box">
                            <view class="price">单价：{{ item.price }}</view>
                        </view>
                    </view>
                    <!-- 人数 -->
                    <u-form-item v-if="type_text !== '计时'" :required="true" :borderBottom="false" :labelWidth="100" label="人数：" prop="people_num" ref="people_num">
                        <u--input  :clearable="false" inputAlign="right" type="digit" placeholder="请输入人数" v-model.lazy="FormData.people_num" border="none"></u--input>
                    </u-form-item>
                    <u-form-item v-if="type_text == '计时'" :required="true" :borderBottom="false" :labelWidth="100" label="人数：" prop="work_time_num" ref="work_time_num">
                        <u--input  :clearable="false" inputAlign="right" type="digit" placeholder="请输入人数" v-model.lazy="FormData.work_time_num" border="none"></u--input>
                    </u-form-item>
                    <!-- 费用支出 -->
                    <u-form-item :required="true" :borderBottom="false" :labelWidth="100" label="费用支出：" prop="dec_fee" ref="dec_fee">
                        <u--input :clearable="false" inputAlign="right" type="digit" placeholder="请输入费用支出" v-model.lazy="FormData.dec_fee" border="none"></u--input>
                    </u-form-item>
                    <!-- 备注 -->
                    <view>
                        <view class="remark">备注:</view>
                        <up-textarea v-model="FormData.remark" placeholder="请输入备注"></up-textarea>
                    </view>
                    <!-- 图片 -->
                    <view>
                        <view class="image">图片:</view>
                        <u-upload :fileList="state.fileList1" @afterRead="imageUpload" @delete="deletePic" name="10" :multiple="true" :maxCount="10">
                        </u-upload>
                    </view>
                    </u--form>
                </scroll-view>
            </view>
        </view>

    </s-layout>

    <!-- 底部保存按钮 -->
    <view>
        <s-button @netWork="submitForm" :text="'保存'" />
    </view>
    <!-- 日期范围 allowSameDay 默认为false 为true的时候可以选择同一天范围  -->
    <!-- <uni-calendar ref="calendar" class="uni-calendar--hook" :clear-date="false" :insert="false" :startDate="time.minDate" :endDate="time.maxDate" :range="true" @confirm="date_confirm" @close="close"/> -->
    <fui-bottom-popup :show="date_show" @close="date_close">
        <!-- :minDate="time.minDate" 最小可选日期 -->
        <fui-calendar :value="time.intraday" :showBtn="true" type="3" :maxDate="time.maxDate" @change="date_confirm" ></fui-calendar>
    </fui-bottom-popup>
    
    <!-- 班次弹出 -->
    <up-picker :closeOnClickOverlay="true" :show="classes_show" :columns="classes_columns" :title="'请选择班次'" @confirm="classes_confirm" @cancel="classes_cancel" @close="classes_close"></up-picker>
 <!-- 底部弹出组件 && 部门弹出 -->
 <s-project-class @selectedData="switchTitle" 
    @subcomponentSearch="subcomponentSearch" :arrayList="projectDataList" ref="popupListRef"
    :searchBoxIsShow="false"   :showGoLink="false"></s-project-class>
</template>

<script setup>
    import sheep from '@/sheep';
    import { ref, reactive } from 'vue';
    import { onLoad } from '@dcloudio/uni-app';
    import { baseUrl } from "@/sheep/config";
    import { isEmpty } from '@/sheep/helper/utils.js'
    const { safeAreaInsets } = uni.getSystemInfoSync()
    const currentTimestamp = new Date().getTime();
    const time = reactive({
        minDate:'',
        maxDate:'',
        monthNum:'13',
        intraday:[]
    })
    // 设置默认日期，最大值为今天，最小值为去年今天
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (month <= 9) {
        month = '0' + month;
    }
    if (day <= 9) {
        day = '0' + day;
    }
    let minyear = year - 1;
    time.minDate = year + '-' + '01' + '-' + '01';
    time.maxDate = (year + 1) + '-01-01';
    time.intraday = [year + '-' + month + '-' + day]
    // time.intraday.push(a)


    onLoad(() => {
        let params={
            is_daily_yield:'1',
            is_all:'0',
            is_include_main:'0'
        }
        projectList(params)
    })
        // 表单数据
    const FormData = reactive({
        department_id:'',      // 部门ID
        date:'',            // 日期
        classes:'',         // 班次  
        people_num:'',      // 人数
        num_price:[],       // 数量单价
        work_time_num:'',   // 工时数
        images:'',          // 图片
        remark:'',          // 备注
        dec_fee:''          // 费用支出
    })
    const price = ref()
    // 日期范围选择
    const num_price_tmp = ref([]);
    // 表单校验
    const rules = {
        department_id:[
            {
                required:true,
                message:'请选择部门',
            },
        ],
        date:[
            {
                required:true,
                message:'请选择时间',
            }
        ],
        classes:[
            {
                required:true,
                message:'请选择班次',
            }
        ],
        people_num:[
            { 
                validator: (rule, value, callback) => {
                    if ((type_text.value == '计件' || type_text.value == '计吨'
                    || type_text.value == '计天') &&  value == '') {
                            callback(new Error('请输入人数'));
                    } else {
                        callback();
                    }
                }, 
                message: '请输入人数'
            }
        ],
        work_time_num:[
            { 
                validator: (rule, value, callback) => {
                    if (type_text.value == '计时' && value == '') {
                            callback(new Error('请输入人数'));
                    } else {
                        callback();
                    }
                }, 
                message: '请输入人数'
            }
        ],
        dec_fee:[
            {
                required:true,
                message:'请输入费用支出',
            }
        ],
    }
    const formRole = ref(null)
    const project_title = ref('')
    const popupListRef = ref()

    const changeNum = (item,index) => {
        FormData.num_price = []
        projectprice.value.map(value => {
            FormData.num_price.push({
                num:value.num,
                price:value.price
            })
        });
	}

    // 保存提交
    const submitForm = () => {
        if (projectprice.value.length == 0) {
            return uni.showToast({
                icon: 'none',
                title: '请联系财务设置单价',
            });
        }
        if (FormData.num_price.length == 0) {
            return uni.showToast({
                icon: 'none',
                title: '请输入数量',
            });
        }
        if (!FormData.num_price.every((i) => i.num)) {
            return uni.showToast({
                icon: 'none',
                title: `${type_text.value == '计时' ? '请输入工时数' : '请输入数量'}`,
            });
        }
        formRole.value.validate().then(async (res)=> {
            // if(isEmpty(FormData.num_price)) {
            //     sheep.$helper.toast('请输入工时数');
            //     return;
            // } else {
            //     for (const item of FormData.num_price) {
            //         if (isEmpty(item.num)) {
            //             sheep.$helper.toast('请输入工时数');
            //             return;
            //         }
            //     }
            // }
            const resust = await sheep.$api.daily_yield.dailyAddAPI(FormData);
            if(resust.code == 1) {
                setTimeout(() => {
                    sheep.$router.back(true)
                },1000)
            } else {
                setTimeout(() => {
                    sheep.$helper.toast(resust.msg);
                    // uni.showToast({
                    //     title:resust.msg,
                    //     icon:'none'
                    // })
                },1000)
            }
        }).catch((err) => {
        })
        return false
        formRole.value.validate().then(async (res)=> {
            if (type_text.value == '计天') {
            if (FormData.people_num == '') {
                return uni.showToast({
                    icon: 'none',
                    title: '请输入人数',
                });
            }
        }
        if (type_text.value == '计时') {
            if (FormData.work_time_num == '') {
                return uni.showToast({
                    icon: 'none',
                    title: '请输入人数',
                });
            }
        }
        if (type_text.value == '计吨') {
            if (FormData.people_num == '') {
                return uni.showToast({
                    icon: 'none',
                    title: '请输入人数',
                });
            }
        }
        if (type_text.value == '计件') {
            if (FormData.people_num == '') {
                return uni.showToast({
                    icon: 'none',
                    title: '请输入人数',
                });
            }
        }

        if (FormData.num_price.length == 0) {
            return uni.showToast({
                icon: 'none',
                title: '请输入数量',
            });
        } else {}
        if (!FormData.num_price.every((i) => i.num)) {
            return uni.showToast({
                icon: 'none',
                title: `${type_text.value == '计时' ? '请输入工时数' : '请输入数量'}`,
            });
        }

            const resust = await sheep.$api.daily_yield.dailyAddAPI(FormData);
            if(resust.code == 1) {
                setTimeout(() => {
                    uni.navigateBack()
                },1000)
            } else {
                setTimeout(() => {
                    uni.showToast({
                        title:resust.msg,
                        icon:'none'
                    })
                },1000)
            }
        }).catch((err) => {
            uni.showToast({
                title:'请仔细核对内容！',
                icon:'none',
                duration:1000
            })
        })
    }

    // 切换部门
    const projectprice = ref([])
    const projectprice_default = ref([])
    const type_text = ref('')
    const project = ref()
    const projectSwitch = () => {
        popupListRef.value.open()
    }
    const switchTitle = (item) => {
        project.value = item
        project_title.value = item.jointTitles
        FormData.department_id = item.id
        projectprice.value = item.num_price
        projectprice_default.value = item.num_price
        // price.value = item.projectprice.price
        type_text.value = item.type_text
        num_price_tmp.value = []
        projectprice.value.forEach((item,key) => {
            num_price_tmp.value['num_price'+key] = ''


        //     rules['num_price_tmp']['num_price'+key] = [
        //     {
        //         required:true,
        //         message:'请输入数量'+key,
        //     }
        // ]
        });
        classes_title.value = ''
        FormData.classes = ''

        
    }
    // 调用接口：获取项目列表
    const projectDataList = ref([])

    // 封装项目列表接口
    const projectList = async (params = null) => {
       const res = await sheep.$api.app.getDepartment(params);
        projectDataList.value = res.data;
    };

  
    // 项目周期弹出
    const date_show = ref(false)
    const date_mode = ref('range')
        // 选择完成
    const date_confirm = (e) => {
        // if(e.range.data.length < 2) {
        //     FormData.date= `${e.fulldate} - ${e.fulldate}`
        // } else {
        //     FormData.date= `${e.range.data[0]} - ${e.range.data[e.range.data.length - 1]}`
        // }
        FormData.date = `${e.value[0]} - ${e.value[e.value.length - 1]}`
        date_show.value = false
    }
        // 关闭
    const date_close = () => {
        date_show.value = false
    }
        // 打开
    const dateRange = () => {
        date_show.value = true
    }

    // 班次弹出
    const classes_title = ref('') 
    const classes_show = ref(false)
    const classes_columns = ref([['早班','晚班','半夜班','出港']])
        // 打开
    const SoonerOrLater = () => {
        if(FormData.department_id == '') {
            return false
        }

        if(FormData.department_id == '7') {
            classes_columns.value = [['早班','晚班','半夜班','出港','航空装卸']]
        } else if(FormData.department_id == '23') {
            classes_columns.value = [['早班','晚班','中班']]
        } else {
            classes_columns.value = [['早班','晚班']]
        }
        classes_show.value = true
    }
        // 确定
    const classes_confirm = (e) => {
        classes_title.value = e.value[0]
        switch (classes_title.value) {
            case '早班':
                FormData.classes = '1'
                break;
            case '晚班':
                FormData.classes = '2'
                break;
            case '出港':
                FormData.classes = '3'
            break;
            case '半夜班':
                FormData.classes = '4'
            break;
            case '航空装卸':
                FormData.classes = '5'
            break;
            case '中班':
                FormData.classes = '6'
        }
        classes_close()
    }
        // 关闭
    const classes_close = () => {
        classes_show.value = false
    }
        // 取消按钮
    const classes_cancel = () => {
        classes_close()
    }

    // 上传图片逻辑
    const state = reactive({
        fileList1:[]
    })
    // 删除图片
    const deletePic = (event) => {
        state.fileList1.splice(event.index, 1);
    };

    // 新增图片
    const imageUpload = async (event) => {
        let lists = [].concat(event.file);
        let fileListLen = state.fileList1.length;
        lists.map((item) => {
            state.fileList1.push({
            ...item,
            status: 'uploading',
            message: '上传中',
            });
        });
        for (let i = 0; i < lists.length; i++) {
            const url = await uploadFilePromise(lists[i].url)
            let item = state.fileList1[fileListLen];
            state.fileList1.splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: sheep.$url.cdn(url),
            });
            fileListLen++;
        }
        FormData.images = postData.value
    };
    const postData = ref([])
        async function uploadFilePromise(tempUrl) {
            let { url } = await sheep.$api.app.upload(tempUrl, 'ugc');
            postData.value.push(url);
        return url;
    };

</script>

<style lang="scss" scoped>

    :deep(.u-form-item__body.data-v-b4fd400b){
        height: 80rpx;
        margin-bottom:10rpx;
        background-color: #F9FAFF;
    }

    :deep(.u-textarea.data-v-31706dd7) {
        background-color: #F9FAFF;
        padding: 0;
    }

    // uview 内部样式 up-textarea 文字距离
    :deep(.u-textarea__field.data-v-31706dd7) {
        margin-top: 30rpx;
        margin-left: 30rpx;
    }

    // uview 内部样式 输入内容右边间距
    :deep(.u-input__content__field-wrapper__field.data-v-5904192e) {
        margin-right: 20rpx;
    }

    // uview 内部样式 label左边间距
    :deep(.u-form-item__body__left.data-v-b4fd400b) {
        margin-left: 20rpx;
    }

    // uview 内部样式 label字体粗细
    :deep(.u-form-item__body__left__content__label.data-v-b4fd400b) {
        font-weight: $uni-font-weight;
    }

    // 最大盒子
    .container {
        width: 100%;
        background-size: cover; /* 或 contain */
    }
    // 版心
    .area {
        width: calc(100% - 40rpx);
        margin: 0 20rpx;
    }

    // 表单盒子
    .form_box {
        width: calc(100% - 100rpx);
        padding: 60rpx 30rpx;
        margin-top: 20rpx;
        border-radius: 16rpx;
        background-color: #FFFFFF;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
        // 右间距
        .right_margin {
            margin-right: 20rpx;
        }
    }

    .date_range {
            height: 64rpx;
            width: 420rpx;
            border-radius: 16rpx;
            border: 4rpx solid #1241E2;
            display: flex;
            align-items: center;
            // 图片
            .date_image {
                width: 28rpx;
                height: 28rpx;
                margin-left: 20rpx;
                margin-right: 12rpx;
                image {
                    width: 100%;
                    height: 100%;
                }
            }
        }

    // 时间
    .range_time {
        font-family: PingFangSC;
        color: $uni-color-primary;
        font-weight: $uni-font-weight;
       font-size:$uni-font-size-26;
        font-style: normal;
        text-decoration: none;
        text-align: right;
    }

    // 收入盒子
    .message {
        display: flex;
        justify-content: space-between; /* 左右对齐 */
        width: 100%;
        height: 48rpx;
        margin: 30rpx 0;
        font-family: PingFangSC;
        color: $uni-text-color;
        font-weight: $uni-font-weight;
        font-size: 34rpx;
        font-style: normal;
        text-decoration: none;
        position: relative;
        .glide {
            width: 68rpx;
            height: 14rpx;
            border-radius: 5px;
            background-color: rgba(0, 56, 247, 0.5);
            position: absolute;
            bottom: 0;
            left: 0;
        }
    }

        // 备注
        .remark {
            width: 100%;
            height: 100rpx;
            line-height: 100rpx;
            font-family: PingFangSC;
            color: $uni-text-color;
            font-weight: $uni-font-weight;
            font-size: 30rpx;
            font-style: normal;
            text-decoration: none;
        }

        // 图片
        .image {
            width: 100%;
            height: 100rpx;
            line-height: 100rpx;
            font-family: PingFangSC;
            color: $uni-text-color;
            font-weight: $uni-font-weight;
            font-size: 30rpx;
            font-style: normal;
            text-decoration: none;
        }

        // 数量盒子
        .num_price {
            display: flex;
            justify-content: space-between;
            align-items: center;
            // 输入框盒子
            .input_box {
                width: 450rpx;
                height: 100%;
            }
            // 单价盒子
            .price_box {
                height: 100%;
                margin-right: 10rpx;
                // 单价
                .price {
                    height: 90rpx;
                    line-height: 80rpx;
                    font-family: PingFangSC;
                    color: $uni-color-primary;
                    font-weight: $uni-font-weight;
                   font-size:$uni-font-size-26;
                    font-style: normal;
                    text-decoration: none;
                }
            }
        }
        
</style>


